package cn.willbj.brief.hootl.threads.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @see java.util.concurrent.Executors
 *
 */
public class CallableDemo {
	public static void main(String[] args) {
		
		ThreadPoolExecutor executor = new ThreadPoolExecutor(6, 10, 1l, TimeUnit.SECONDS, 
				new ArrayBlockingQueue<>(100), new ThreadPoolExecutor.CallerRunsPolicy());
		
		Callable<String> task = new Callable<String>() {
			@Override
			public String call() throws Exception {
				Thread.sleep(1000);
				return Thread.currentThread().getName();
			}
		};
		List<Future<String>> futureList = new ArrayList<>();;
		for (int i = 0; i < 10; i++) {
            //提交任务到线程池
            Future<String> future = executor.submit(task);
			//将返回值 future 添加到 list，我们可以通过 future 获得 执行 Callable 得到的返回值
            futureList.add(future);
        }
		
		for (Future<String> fut : futureList) {
			try {
				System.out.println(new Date() + "::" + fut.get());
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
			}
		}
		
		//关闭线程池
		executor.shutdown();
		
	}

}
